// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <algorithm>
#include <cstdint>
#include <memory>
#include <vector>

#include <nebula/core/array.h>
#include <nebula/core/chunk_resolver.h>
#include <nebula/compute/kernels/codegen_internal.h>

namespace nebula::compute::internal {

    // The target chunk in a chunked array.
    struct ResolvedChunk {
        // The target array in chunked array.
        const Array *array;
        // The index in the target array.
        const int64_t index;

        ResolvedChunk(const Array *array, int64_t index) : array(array), index(index) {}

    public:
        bool is_null() const { return array->is_null(index); }

        template<typename ArrowType, typename ViewType = GetViewType<ArrowType>>
        typename ViewType::T value() const {
            using LogicalArrayType = typename TypeTraits<ArrowType>::ArrayType;
            auto *typed_array = turbo::checked_cast<const LogicalArrayType *>(array);
            return ViewType::LogicalValue(typed_array->get_view(index));
        }
    };

    class ChunkedArrayResolver {
    private:
        ::nebula::internal::ChunkResolver resolver_;
        std::vector<const Array *> chunks_;

    public:
        explicit ChunkedArrayResolver(const std::vector<const Array *> &chunks)
                : resolver_(chunks), chunks_(chunks) {}

        ChunkedArrayResolver(ChunkedArrayResolver &&other) = default;

        ChunkedArrayResolver &operator=(ChunkedArrayResolver &&other) = default;

        ChunkedArrayResolver(const ChunkedArrayResolver &other) = default;

        ChunkedArrayResolver &operator=(const ChunkedArrayResolver &other) = default;

        ResolvedChunk resolve(int64_t index) const {
            const auto loc = resolver_.resolve(index);
            return {chunks_[loc.chunk_index], loc.index_in_chunk};
        }
    };

    inline std::vector<const Array *> get_array_pointers(const ArrayVector &arrays) {
        std::vector<const Array *> pointers(arrays.size());
        std::transform(arrays.begin(), arrays.end(), pointers.begin(),
                       [&](const std::shared_ptr<Array> &array) { return array.get(); });
        return pointers;
    }

}  // namespace nebula::compute::internal
